package oj;

import java.util.LinkedList;
import java.util.List;
import java.util.Stack;

public class Num145 {
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> ret=new LinkedList<>();
        if(root==null){
            return ret;
        }
        Stack<TreeNode> stack=new Stack<>();
        //当前需要处理的节点
        TreeNode cur=root;
        //最近一次已经访问过的节点
        TreeNode prev=null;
        while (cur!=null || !stack.isEmpty()){
            while (cur!=null){
                stack.push(cur);
                cur=cur.left;
            }
            cur=stack.pop();
            if(cur.right==null || prev==cur.right){
                ret.add(cur.val);
                prev=cur;
                cur=null;
            }else {
                stack.push(cur);
                cur=cur.right;
            }
        }
        return ret;
    }
}
